package framework.file.scan;

import framework.bean.NeedScanPackageBean;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author 马洁
 * @date 2020/3/11 - 13:48
 */
public class FileScan {
    private static final int DEFAULT_SIZE = 30;
    private NeedScanPackageBean scanPackageBean;
    private List<File> files;

    public FileScan(NeedScanPackageBean needScanPackageBean,
                    int setInitSize) {
        this.scanPackageBean = needScanPackageBean;
        initSet(setInitSize);
    }

    public FileScan(NeedScanPackageBean scanPackageBean) {
        this(scanPackageBean, DEFAULT_SIZE);
    }

    private void initSet(int size) {
        files = new ArrayList<>(size);
    }

    public List<File> startScan() {
        enumerate(new File(scanPackageBean.getAllPackageName()));

        return files;
    }

    /**
     * 如果传递过来的是文件夹, 找到文件夹下面的所有非文件夹的上一次文件夹        <br>
     * 例如：                                                      <br>
     * com/my/LoginController.java                            <br>
     * 返回的就是                                               <br>
     * com/my
     *
     * @param file 文件
     */
    private void enumerate(File file) {
        File[] directory = file.listFiles();

        if (Objects.nonNull(directory)) {
            for (File listFile : directory) {
                if (listFile.isDirectory()) {
                    enumerate(listFile);
                } else {
                    files.add(listFile);
                }
            }
        }
    }

}
